const pluginName = 'SemiWebpackPlugin';

// 解决 ssr 加载资源的问题
class SemiWebpackPlugin {
  apply(compiler) {
    compiler.hooks.emit.tapAsync(pluginName, (compilation, cb) => {
      //可遍历出所有的资源名
      for (var filename in compilation.assets) {
        console.log('name==', filename);
      }
      compilation.chunks.forEach(function (chunk) {
        chunk.files.forEach(function (filename) {
          // compilation.assets 存放当前所有即将输出的资源
          // 调用一个输出资源的 source() 方法能获取到输出资源的内容
          let source = compilation.assets[filename].source();
          source = source.replace(/@douyinfe\/semi-ui/g, '@douyinfe/semi-ui/dist/umd/semi-ui.js');
          compilation.assets[filename] = {
            source: function () {
              return source;
            },
            size: function () {
              return source.length;
            }
          };
        });
      });
      cb();
    });
    compiler.hooks.done.tap(pluginName, compilation => {
      console.log('webpack 构建完毕！');
    });
  }
}

module.exports = { SemiWebpackPlugin };
